package com.glkj.vipsystem.modules.merchant.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.glkj.vipsystem.common.utils.PageUtils;
import com.glkj.vipsystem.common.utils.Query;
import com.glkj.vipsystem.common.utils.R;
import com.glkj.vipsystem.common.validator.ValidatorUtils;
import com.glkj.vipsystem.common.validator.group.AddGroup;
import com.glkj.vipsystem.common.validator.group.UpdateGroup;
import com.glkj.vipsystem.entity.gen.KaidanUser;
import com.glkj.vipsystem.modules.sys.controller.AbstractController;
import com.glkj.vipsystem.service.IKaidanUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 开单人员Controller
 *
 * @author LiMuchan
 */
@RestController
@RequestMapping("/merchant/kaidan-user")
public class KaidanUserController extends AbstractController {

    @Resource
    private IKaidanUserService kaidanUserService;

    /**
     * 列表
     */
    @RequestMapping(value = "/list")
    @RequiresPermissions({"merchant:kaidan:user"})
    public R list(@RequestParam Map<String, Object> params) {
        String name = (String) params.get("name");
        String mobile = (String) params.get("mobile");
        String companyId = (String) params.get("companyId");
        Wrapper<KaidanUser> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("*,(SELECT company_name FROM t_company WHERE id = t_kaidan_user.company_id) as company_name");
        wrapper.orderBy("id desc");
        // 数据权限控制
        if (isCompanyRole()) {
            // 公司管理员
            String username = getUser().getUsername();
            wrapper.where("company_id = (select id from t_company where `username` = '" + username + "')");
        } else if (isEmployeeRole()) {
            // 店铺员工
            String username = getUser().getUsername();
            wrapper.where("company_id = (select company_id from t_employee where `username` = '" + username + "')");
        }
        if (StringUtils.isNotBlank(companyId)) {
            wrapper.eq("company_id", companyId);
        }
        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(mobile)) {
            wrapper.like("mobile", mobile);
        }
        Page<KaidanUser> page = kaidanUserService.selectPage(
                new Query<KaidanUser>(params).getPage(),
                wrapper
        );
        return R.ok().put("page", new PageUtils(page));
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{id}")
    @RequiresPermissions({"merchant:kaidan:user"})
    public R detail(@PathVariable("id") Integer id) {
        return R.ok().put("item", kaidanUserService.selectById(id));
    }

    /**
     * 保存新增
     */
    @RequestMapping(value = "/save")
    @RequiresPermissions({"merchant:kaidan:user"})
    public R save(@RequestBody KaidanUser form) {
        ValidatorUtils.validateEntity(form, AddGroup.class);
        try {
            kaidanUserService.insert(form);
        } catch (DuplicateKeyException e) {
            return R.error("电话重复");
        }
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @RequiresPermissions({"merchant:kaidan:user"})
    public R update(@RequestBody KaidanUser form) {
        ValidatorUtils.validateEntity(form, UpdateGroup.class);
        try {
            kaidanUserService.updateById(form);
        } catch (DuplicateKeyException e) {
            return R.error("电话重复");
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @RequiresPermissions({"merchant:kaidan:user"})
    public R delete(@RequestBody Integer[] ids) {
        if (ids != null && ids.length > 0) {
            kaidanUserService.deleteBatchIds(Arrays.asList(ids));
        }
        return R.ok();
    }

    /**
     * 获取公司开单人员
     */
    @RequestMapping(value = "/getByCompany")
    public R getByCompany(@RequestParam("companyId") Integer companyId) {
        if (companyId == null) {
            return R.ok().put("data", new ArrayList<>());
        }
        Wrapper<KaidanUser> wrapper = new EntityWrapper<KaidanUser>();
        wrapper.orderBy("id desc");
        // 数据权限
        if (isCompanyRole()) {
            // 公司管理员
            String username = getUser().getUsername();
            wrapper.where("company_id = (select id from t_company where `username` = '" + username + "')");
        } else if (isEmployeeRole()) {
            // 店铺员工
            String username = getUser().getUsername();
            wrapper.where("company_id = (select company_id from t_employee where `username` = '" + username + "')");
        } else {
            wrapper.eq("company_id", companyId);
        }
        List<KaidanUser> users = kaidanUserService.selectList(
                wrapper
        );
        return R.ok().put("data", users);
    }
}
